<script type="module">
  import { createApp } from '../src'

  const treeData = {
    name: 'My Tree',
    children: [
      { name: 'hello' },
      { name: 'wat' },
      {
        name: 'child folder',
        children: [
          {
            name: 'child folder',
            children: [{ name: 'hello' }, { name: 'wat' }]
          },
          { name: 'hello' },
          { name: 'wat' },
          {
            name: 'child folder',
            children: [{ name: 'hello' }, { name: 'wat' }]
          }
        ]
      }
    ]
  }

  function TreeItem(model) {
    return {
      $template: '#item-template',
      model,
      open: false,
      get isFolder() {
        return model.children && model.children.length
      },
      toggle() {
        if (this.isFolder) {
          this.open = !this.open
        }
      },
      changeType() {
        if (!this.isFolder) {
          model.children = []
          this.addChild()
          this.open = true
        }
      },
      addChild() {
        model.children.push({
          name: 'new stuff'
        })
      }
    }
  }

  createApp({
    TreeItem,
    treeData
  }).mount()
</script>

<template id="item-template">
  <div :class="{ bold: isFolder }" @click="toggle" @dblclick="changeType">
    <span>{{ model.name }}</span>
    <span v-if="isFolder">[{{open ? '-' : '+'}}]</span>
  </div>
  <ul v-show="open" v-if="isFolder">
    <li v-for="model in model.children" v-scope="TreeItem(model)"></li>
    <li class="add" @click="addChild">+</li>
  </ul>
</template>

<p>Double click an item to turn it into a folder.</p>
<ul v-scope>
  <li class="item" v-scope="TreeItem(treeData)"></li>
</ul>

<style>
  body {
    font-family: Menlo, Consolas, monospace;
    color: #444;
  }
  .item {
    cursor: pointer;
  }
  .bold {
    font-weight: bold;
  }
</style>
